<!-- vue模板 -->
<template>
  <div class="container">
    <div class="title">基础设置</div>
    <div>
      仓库名
      <el-select
        v-model="ckName"
        :options="options"
        placeholder="仓库"
        style="width: 240px"
        @change="handleFilterChange"
      />
      库区名称
      <el-input
        v-model="kuName"
        style="width: 200px"
        placeholder="库区"
        clearable
        @input="handleFilterChange"
      />
      <!--@input绑定到handleFilterChange实现自动更新  -->
      <el-button type="primary" plain @click="handleQuery">查询</el-button>
      <el-button type="success" plain @click="tiaoAdd">添加库区</el-button>

      <el-button v-print="printOptions">打印</el-button>
    </div>

    <el-table
      :data="tableData"
      stripe
      border
      class="centered-text-table centered-table"
      id='printContent'
    >
      <el-table-column type="index" label="序号" width="100" />
      <el-table-column prop="ckname" label="仓库名" width="180" />
      <el-table-column prop="kuname" label="库区名" width="180" />
      <el-table-column prop="warmarea" label="温区" width="180" />
      <el-table-column label="操作" width="280">
        <template v-slot="{ row }">
          <el-button type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" @click="handleDelete(row.id)">删除</el-button>
          <el-button type="info">添加货位</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<!-- 组件逻辑-->
<script setup>
import { ref, onMounted } from "vue";
import { queryKU , ckname,deleteKU} from "@/api/set/product.js";
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'; // 导入路由钩子
// import { log } from "console";
//响应式对象
const tableData = ref([]);
//库区名
const kuName = ref("");
// 仓库
const ckName = ref("");
// 仓库选择框选项（初始为空数组）
const options = ref([])
// 分页相关参数
const currentPage = ref(1); //页码
const pageSize = ref(5); //每页条数
const totalCount = ref(0); //总条数
// 防抖计时器
let debounceTimer = null;
// 初始化路由实例
const router = useRouter();

//数据展示
async function init() {
  let params = {
    page: currentPage.value,
    pageSize: pageSize.value,
    ckName: ckName.value,
    kuName: kuName.value
  };
  try {
    let res = await queryKU(params);
    console.log(res);
    //判断接口状态
    if (res.status == 200) {
      tableData.value = res.data.list;
      totalCount.value = res.data.total;
    }
  } catch (error) {
    console.error("数据查询失败:", error);
  }
}

//周期函数渲染调用
onMounted(() => {
  init();
  cangkuname();
});

//仓库选择框
async function cangkuname() {
  try {
    const res = await ckname();
    console.log(res);
    if (res.code == 200) {
      // 添加全部选项
      const allOption={
        value: "",
        label: "全部"
      }
      //将"全部"选项添加到数组最前面，再拼接接口返回的数据
        options.value = [
          allOption,  // 先添加"全部"选项
          ...res.data.map(item => ({  // 再添加接口返回的仓库
            value: item.name,
            label: item.name
        }))
      ];
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
  }
  //初始化表格数据
  await init();
}


// 分页相关参数
// 动态更新相关参数
const handleSizeChange = newSize => {
  console.log("每页条数变更为" + newSize);
  pageSize.value = newSize;
  currentPage.value = 1; // 页大小变化时重置到第一页
  init(); // 自动调用查询
};
const handleCurrentChange = newPage => {
  console.log("页码变更为" + newPage);
  currentPage.value = newPage;
  init();
};

// 查询功能
// 处理查询按钮点击
const handleQuery = () => {
  currentPage.value = 1; // 查询时重置到第一页
  init();
};
// 筛选条件变化处理（带防抖）
const handleFilterChange = () => {
  // 清除之前的计时器
  if (debounceTimer) {
    clearTimeout(debounceTimer);
  }
  // 500ms防抖，避免输入过程中频繁请求
  debounceTimer = setTimeout(() => {
    currentPage.value = 1; // 筛选条件变化，重置到第一页
    init();
  }, 500);
}

//删除功能
const handleDelete = (id) => {
   // 存储当前要删除的ID
   const deleteId = id;

  ElMessageBox.confirm(
    '你确定要删除吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      try {
        const res=await deleteKU(deleteId);
        if (res.code==200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          });
          init();
        }else{
          ElMessage({
             type: 'error',
             message: '删除失败',
           })
        }
      } catch (error) {
            console.error('删除接口调用失败：', error);
            ElMessage({
              type: 'error',
              message: '删除失败，请稍后重试',
            });
      }
      
    })
    .catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消删除', // 修正提示文字，取消操作不是失败
          })
    })
}

//带参数跳转
const handleEdit = (row) => {
  console.log('----------row:', row)

  router.push({  
    name: 'edit-area',
    query: {
      
      ckName: row.ckname,        
      warmArea: row.warmarea,
      id: row.id,
      kuName: row.kuname
    }
  });
}

//点击添加跳转
const tiaoAdd = () => {
  router.push({ name: 'edit-area' });
}



//打印
const printOptions = {
  id: 'printContent', // 要打印的元素ID
  popTitle: '打印标题', // 打印页标题
  extraCss: 'https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css', // 额外的CSS
  extraHead: '<meta charset="UTF-8">', // 额外的头部信息
  beforeOpenCallback(vm) {
    console.log('打开之前')
  },
  openCallback(vm) {
    console.log('执行了打印')
  },
  closeCallback(vm) {
    console.log('关闭了打印工具')
  }
}
</script>

<!-- 组件样式 -->
<style scoped>
.container {
  padding: 20px;
  /* 可添加 max-width: 1200px; 限制最大宽度，避免过宽 */
  max-width: 1200px;
  margin: 0 auto; /* 让容器自身居中，避免左右留白过大 */
}

.title {
  text-align: center; /* 文字居中 */
  font-size: 1.25rem;
  font-weight: 600;
  margin-bottom: 20px;
}

.centered-table {
  width: 100%; /* 占满父容器宽度 */
  margin: 0 auto;
}

/* 响应式调整：屏幕小于1000px时自适应 */
@media (max-width: 1000px) {
  .centered-table {
    width: 100%;
  }
}

/* 表头文字居中 */
:deep(.centered-text-table .el-table__header th) {
  text-align: center !important;
}

/* 表格内容文字居中 */
:deep(.centered-text-table .el-table__body td) {
  text-align: center !important;
}

.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
